package com.example.util;

import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import static com.aliyun.teautil.Common.toJSONString;

@Data
@Component
@ConfigurationProperties(prefix = "aliyun.sms")
public class Sample {

    private String ALIBABA_CLOUD_ACCESS_KEY_ID;
    private String ALIBABA_CLOUD_ACCESS_KEY_SECRET;
    private String ENDPOINT;
    private String TEMPLATECODE;
    private String SIGNNAME;


    private  Client client;

    public  Client createClient() throws Exception {
        if (client==null) {
            Config config = new Config();
            config.setType("access_key")
                    // 配置 AccessKey ID，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                    .setAccessKeyId(ALIBABA_CLOUD_ACCESS_KEY_ID)
                    // 配置 AccessKey Secret，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                    .setAccessKeySecret(ALIBABA_CLOUD_ACCESS_KEY_SECRET);

            // 配置 Endpoint
            config.endpoint = ENDPOINT;
            client = new Client(config);
        }
        return client;

    }




    public SendSmsResponse sendSms(String phoneNumbers,String templateParam) throws Exception {
        Client client1 = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumbers)
                .setSignName(SIGNNAME)
                .setTemplateCode(TEMPLATECODE)
                .setTemplateParam(templateParam);
        SendSmsResponse sendSmsResponse = client1.sendSms(sendSmsRequest);
        return sendSmsResponse;
    }

//
//
//    public static void main(String[] args) throws Exception {
//        // 初始化请求客户端
//        Client client = Sample.createClient();
//
//        // 构造请求对象，请填入请求参数值
//        SendSmsRequest sendSmsRequest = new SendSmsRequest()
//                .setPhoneNumbers("1390000****")
//                .setSignName("阿里云")
//                .setTemplateCode("SMS_15305****")
//                .setTemplateParam("{\"name\":\"张三\",\"number\":\"1390000****\"}");
//
//        // 获取响应对象
//        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
//
//        // 响应包含服务端响应的 body 和 headers
//        System.out.println(toJSONString(sendSmsResponse));
//    }
}